package com.sctvcloud.renhe.tts;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.ui.activities.NewesDetailActivity;
import com.sctvcloud.renhe.ui.dialog.VoiceSetFragment;

import java.util.List;

public class SpeakUtils {
    private Context context;
    private static final String APPID = "5976a3bb";
    private SpeechSynthesizer mTts;
    private SharedPreferences mSharedPreferences;
    private String mEngineType;
    private List<String> speakList;
    private int speakingIndex = 0;
    private OnSpeakComplementListener listener;
    private int speakType = 0;//0 为单个字符串，1为字符串列表
    private String speed = "";
    private String template = "";

    public SpeakUtils(Context context, OnSpeakComplementListener li) {
        this.context = context;
        SpeechUtility.createUtility(context, SpeechConstant.APPID + "=" + APPID);
        listener = li;
        // 缓存语音合成速度
        speed = (String) SharedPreferencesUtil.getParam(context, Constances.VOICE_SPEED_KEY, Constances.MID_SPEED);
        template = (String) SharedPreferencesUtil.getParam(context, Constances.VOICE_TEMPLATE_KEY, VoiceSetFragment.PT_TEMPLATE);
        initTTS();
    }

    private void initTTS() {
        mTts = SpeechSynthesizer.createSynthesizer(context, null);
        mSharedPreferences = context.getSharedPreferences(TtsSettings.PREFER_NAME, context.MODE_PRIVATE);
        FlowerCollector.onEvent(context, "tts_play");
        mEngineType = SpeechConstant.TYPE_CLOUD;
        setParam();
    }

    public boolean refreshVoiceSet() {
        // 缓存语音合成速度
        String newSpeed = (String) SharedPreferencesUtil.getParam(context, Constances.VOICE_SPEED_KEY, Constances.MID_SPEED);
        String newTemplate = (String) SharedPreferencesUtil.getParam(context, Constances.VOICE_TEMPLATE_KEY, VoiceSetFragment.PT_TEMPLATE);
        if (speed.equalsIgnoreCase(newSpeed) && template.equalsIgnoreCase(newTemplate)) {
            return false;
        } else {
            setParam();
            return true;
        }
    }

    /**
     * 设置参数
     */
    private void setParam() {
        //清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        mTts.setParameter(SpeechConstant.PARAMS, "rdn=2");


        //根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            //设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, template);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", speed));
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "100"));
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            //设置本地合成发音人voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            //TODO本地合成不设置语速、音调、音量，默认使用语记设置 开发者如需自定义参数，请参考在线合成参数设置

        }

        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
        //设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
        //设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        //注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {
// show Tip("开始播放");
        }

        @Override
        public void onSpeakPaused() {
// showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
// showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int i, int i1, int i2, String s) {

        }

        @Override
        public void onSpeakProgress(int i, int i1, int i2) {

        }

        @Override
        public void onCompleted(SpeechError speechError) {
            if (speakType == 0) {
                if (null != listener) {
                    listener.OnComplement();
                }
            } else if (speakType == 1) {
                if (null != mTts && null != speakList && speakList.size() > 0) {
                    speakingIndex++;
                    if (speakList.size() > speakingIndex) {
                        mTts.startSpeaking(speakList.get(speakingIndex), mTtsListener);
                    } else if (null != listener) {
                        listener.OnComplement();
                    }
                }
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    public void speak(String text) {
        if (null != mTts && !TextUtils.isEmpty(text)) {
            speakType = 0;
            int code = mTts.startSpeaking(text, mTtsListener);
//            if (code != ErrorCode.SUCCESS) {
//                if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
//                    Toast.makeText(context, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(context, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show();
//                }
//            }
        }
    }

    public void speakList() {
        if (null != mTts && null != speakList && speakList.size() > 0) {
            speakType = 1;
            speakingIndex = 0;
            mTts.startSpeaking(speakList.get(speakingIndex), mTtsListener);
        }
    }

    public void setSpeakList(List<String> speakList) {
        this.speakList = speakList;
    }

    /**
     * 停止播报语音
     */
    public void stop() {
        if (mTts != null) {
            mTts.stopSpeaking();
        }
    }

    /**
     * 暂停播报语音
     */
    public void pauseSpeak() {
        if (mTts != null) {
            mTts.pauseSpeaking();
        }
    }


    public boolean isSpeaking() {

        if (mTts == null) {
            return false;
        }
        return mTts.isSpeaking();
    }

    /**
     * 继续播放
     */
    public void speakResume() {
        if (mTts != null) {
            mTts.resumeSpeaking();
        }
    }

    /**
     * 销毁语音合成
     */
    public void onDestroy() {
        if (mTts != null) {
            mTts.stopSpeaking();
            mTts.destroy();
        }
    }

    public interface OnSpeakComplementListener {
        void OnComplement();
    }
}
